package com.pt25.base.model.websocket.handler;

import com.pt25.base.model.websocket.WebsocketHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


/**
 * 清理，关闭，异常处理等
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class GlobalHandler extends ChannelInboundHandlerAdapter {

    @Resource
    private WebsocketHandler websocketHandler;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        try {
            websocketHandler.handleErrorMessage(ctx, cause);
        } catch (Exception e) {
            log.error("exceptionCaught-error", e);
        } finally {
            // 记录异常
            log.error("Unhandled exception occurred in channel id={}", ctx.channel().id(), cause);
            // 关闭通道
            if (ctx.channel().isOpen()) {
                ctx.close();
            }
        }
    }

    /**
     * websocket连接创建
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        try {
            websocketHandler.handleChannelActive(ctx);
        } catch (Exception e) {
            log.error("channelActive-error", e);
        } finally {
            ctx.fireChannelActive();
            log.info("channelActive");
        }
    }

    /**
     * websocket连接断开
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        try {
            websocketHandler.handleChannelInactive(ctx);
        } catch (Exception e) {
            log.error("channelInactive-error", e);
        } finally {
            ctx.fireChannelInactive();
            log.info("channelInactive");
        }
    }
}
